﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LeadVinaglue.Models.ViewPages;
using LeadVinaglue.Models;
using System.Web.Routing;
using System.Web.Security;
using LeadVinaglue.Utility;

namespace LeadVinaglue.Areas.Management.Controllers
{
    public class UserListController : Controller
    {
        EFRoleProvider provider = new EFRoleProvider();
        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // Create an instance of user manage
        LeadVinaglue.Repository.UserManagementRepository repository = new LeadVinaglue.Repository.UserManagementRepository();

        //
        // GET: /Management/Home/
        [Authorize(Roles="SuperAdministrator")]
        public ActionResult Index()
        {
            UserManagementModel model = new UserManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", "Administrator", string.Empty, "CreationDate", "desc");
            return View(model);
        }

        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult AddUser()
        {
            UserManagementModel model = new UserManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator");

            return View(model);
        }

        // Add new user with role Admin
        // Throw exceiption if false
        // Redirect to action index if success
        [HttpPost]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult AddUser(FormCollection form)
        {
            Repository.UserRepository userRepository = new Repository.UserRepository();
            User model = new User();

            try
            {
                // Get information from form submit
                // Parse data
                model.Username = form["Email"].ToString();
                model.Email = form["Email"].ToString();
                model.Password = EncryptionData.Encryption(form["Password"].ToString());

                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Username, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    User temp = userRepository.GetSingle(model.Username);

                    if (temp != null)
                    {
                        temp.Fullname = form["Fullname"].ToString();
                        temp.FirstName = form["FirstName"].ToString();
                        temp.LastName = form["LastName"].ToString();
                        temp.Phone = form["Phone"].ToString();
                        temp.PhoneExt = form["PhoneExt"].ToString();
                        temp.Mobile = form["Mobile"].ToString();
                        temp.Fax = form["Fax"].ToString();
                        temp.Address = form["Address"].ToString();
                        temp.City = form["City"].ToString();
                        temp.State = form["State"].ToString();
                        temp.ZipCode = form["ZipCode"].ToString();
                        temp.IsApproved = true;
                        temp.IsLockedOut = false;
                        temp.Active = true;

                        // Update users
                        userRepository.Save(temp);

                        // Add role to users
                        provider.AddUserToRole(temp.Username, "Administrator");
                        provider.AddUserToRole(temp.Username, "ClientAdmin");
                    }

                    return RedirectToAction("Index", "UserList");
                }
            }
            catch
            {
            }

            return RedirectToAction("Index", "UserList");
        }

        // Edit/ID
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult EditUser(int id)
        {
            ViewBag.UserID = id;
            UserManagementModel model = new UserManagementModel();
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", id);

            return View(model);
        }

        // Update users
        [HttpPost]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult EditUser(int id, FormCollection form)
        {
            Repository.UserRepository userRepository = new Repository.UserRepository();

            try
            {
                // Get information from form submit
                // Parse data
                User temp = userRepository.GetSingle(id);

                if (temp != null)
                {
                    if (!string.IsNullOrEmpty(form["Password"].ToString()))
                        temp.Password = EncryptionData.Encryption(form["Password"].ToString());
                    temp.Fullname = form["Fullname"].ToString();
                    temp.FirstName = form["FirstName"].ToString();
                    temp.LastName = form["LastName"].ToString();
                    temp.Phone = form["Phone"].ToString();
                    temp.PhoneExt = form["PhoneExt"].ToString();
                    temp.Mobile = form["Mobile"].ToString();
                    temp.Fax = form["Fax"].ToString();
                    temp.Address = form["Address"].ToString();
                    temp.City = form["City"].ToString();
                    temp.State = form["State"].ToString();
                    temp.ZipCode = form["ZipCode"].ToString();
                    temp.IsApproved = true;
                    temp.IsLockedOut = false;
                    temp.Active = form["Active"] != null ? bool.Parse(form["Active"].ToString()) : false;

                    // Update users
                    userRepository.Save(temp);
                }
            }
            catch
            {
            }

            return RedirectToAction("Index", "UserList");
        }

        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult GetData(string keywords, int pageSize, int pageIndex, string sortBy, string sortOrder, int id, int assignUserId)
        {
            if (keywords.ToUpper() == "SEARCH USERS")
                keywords = string.Empty;

            UserManagementModel model = new UserManagementModel();

            if (id > 0 && assignUserId > 0 && id != assignUserId)
            {
                repository.UpdateAssignUserAndDelete(id, assignUserId);
                model.Error = string.Empty;
            }
            else
                model = repository.GetModel("Administrator", keywords, sortBy, sortOrder, pageSize, pageIndex, id, 0);

            return Json(model, JsonRequestBehavior.AllowGet);
        }
        

        // Delete an account existing on system
        [HttpGet]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult Delete(string keywords, int pageSize, int pageIndex, string sortBy, string sortOrder, int id, int assignUserId)
        {
            if (keywords.ToUpper() == "SEARCH USERS")
                keywords = string.Empty;

            // First: Update Locked/Unlock users
            Repository.UserRepository userRepository = new Repository.UserRepository();
            userRepository.Delete(id);

            // Second: Get data after lock/unlock
            UserManagementModel model = new UserManagementModel();
            model = repository.GetModel("Administrator", keywords, sortBy, sortOrder, pageSize, pageIndex, id, assignUserId);

            return Json(model, JsonRequestBehavior.AllowGet);
        }

        // User settings
        #region #User settings
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult MySetting()
        {
            UserManagementModel model = new UserManagementModel();

            // Get current user id
            var user = new LeadVinaglue.Repository.UserRepository().GetSingle(User.Identity.Name);
            model = repository.GetModel(Helpers.Constant.HOME, "SuperAdministrator", user.ID);

            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "SuperAdministrator")]
        public ActionResult MySetting(FormCollection form)
        {
            LeadVinaglue.Repository.UserRepository repository= new LeadVinaglue.Repository.UserRepository();

            // Get current user id
            var user = repository.GetSingle(User.Identity.Name);
            user.Fullname = form["Fullname"].ToString();
            user.FirstName = form["FirstName"].ToString();
            user.LastName = form["LastName"].ToString();
            if (!string.IsNullOrEmpty(form["Password"].ToString()))
                user.Password = form["Password"].ToString();

            repository.Save(user);

            return RedirectToAction("MySetting");
        }

        #endregion
    }
}
